package github.ziwukun.jsonql.analysis;

import github.ziwukun.jsonql.lang.JSONQL;
import github.ziwukun.jsonql.lang.Limit;
import github.ziwukun.jsonql.orm.Model;
import github.ziwukun.jsonql.orm.ModelProp;
import github.ziwukun.jsonql.orm.Prop;

/**
 * Limit语句分析
 * @author Hugo.Yu
 */
public class ModelAndLimitAnalysistor implements ModelAndQLAnalysistor{

	@Override
	public void analysis(Model model, JSONQL ql) throws AnalysisException {
		Limit limit = ql.limit();
		if(limit != null) {
			analysisModelAndLimit(model,limit);
		}
	}
	
	private void analysisModelAndLimit(Model model,Limit limit) {
		if(model.modelName().equals(limit.model())) {
			throw new AnalysisException("非法的@limit语句{}",limit.toJSONQL());
		}
		
		if(!limit.isChildsEmpty()) {
			for (Limit childLimit : limit.childs()) {
				Prop prop = model.getPropByName(childLimit.model());
				if(prop == null) {
					throw new AnalysisException("非法的@limit语句{}",childLimit.toJSONQL());
				}
				if(!(prop instanceof ModelProp)) {
					throw new AnalysisException("非法的@limit语句{}",childLimit.toJSONQL());
				}
				ModelProp modelProp = (ModelProp)prop;
				analysisModelAndLimit(modelProp.propModel(),childLimit);
			}
		}
	}
}
